package org.dromara.community.controller;

import io.swagger.v3.oas.annotations.Operation;

import org.dromara.comm_lhz.util.QiniuUtil;
import org.dromara.community.entity.AsOrder;
import org.dromara.community.entity.dto.AsOrderDTO;
import org.dromara.community.mapper.AsOrderMapper;
import org.dromara.community.service.AsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("asOrder")
public class AsOrderController {

    @Autowired
    private AsOrderMapper asOrderMapper;

    @Autowired
    private AsOrderService asOrderService;
    @Autowired
    private QiniuUtil qiniuUtil;

    /**
     * 上传图片并添加订单
     */
    @Operation(summary = "上传图片并添加订单")
    @PostMapping("/uploadAndAdd")
    public ResponseEntity<Map<String, Object>> uploadImageAndAddOrder(
        @RequestParam(value = "id", required = false) Long id,
        @RequestParam(value = "file") MultipartFile file,
        @RequestParam(value = "ascommodityId") Long ascommodityId,
        @RequestParam(value = "orderName") String orderName,
        @RequestParam(value = "address") String address,
        @RequestParam(value = "price") Double price,
        @RequestParam(value = "describe") String describe,
        @RequestParam(value = "verificationDeadline") String verificationDeadline,
        @RequestParam(value = "totalPrice") Double totalPrice,
        @RequestParam(value = "state") Integer state
    ) {

        // 用于存储响应数据的哈希映射
        HashMap<String, Object> hashMap = new HashMap<>();

        try {
            // 检查上传的文件是否为空
            if (file.isEmpty()) {
                hashMap.put("message", "文件不能为空");
                return new ResponseEntity<>(hashMap, HttpStatus.BAD_REQUEST);
            }

            // 上传图片到七牛云并获取图片URL
            String imageUrl = qiniuUtil.uploadImage(file);

            // 创建一个新的订单对象并设置各项属性
            AsOrder asOrder = new AsOrder();
            asOrder.setAscommodityId(ascommodityId);
            asOrder.setUrl(imageUrl);
            asOrder.setOrderName(orderName);
            asOrder.setAddress(address);
            asOrder.setPrice(price);
            asOrder.setDescribe(describe);
            asOrder.setVerificationDeadline(verificationDeadline);
            asOrder.setTotalPrice(totalPrice);
            asOrder.setState(state);

            // 保存订单到数据库
            asOrderService.save(asOrder);

            // 设置响应数据，包括成功信息和图片URL
            hashMap.put("message", "添加新的订单");
            hashMap.put("imageUrl", imageUrl);
            return new ResponseEntity<>(hashMap, HttpStatus.OK);
        } catch (Exception e) {
            // 处理过程中发生异常时，设置响应数据为失败信息
            hashMap.put("message", "添加失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传图片并x修改订单
     */
    @Operation(summary = "修改订单")
    @PostMapping("/modification")
    // 上传文件以修改订单信息
    public ResponseEntity<Map<String, Object>> uploadUploadAsOrder(
        @RequestParam(value = "id", required = false) Long id, // 订单ID，用于确定要修改的订单，可选
        @RequestParam(value = "file") MultipartFile file, // 上传的文件，用于更新订单的图片
        @RequestParam(value = "ascommodityId") Long ascommodityId, // 商品ID，用于确定订单中的商品
        @RequestParam(value = "orderName") String orderName, // 订单名称
        @RequestParam(value = "address") String address, // 订单地址
        @RequestParam(value = "price") Double price, // 订单单价
        @RequestParam(value = "describe") String describe, // 订单描述
        @RequestParam(value = "verificationDeadline") String verificationDeadline, // 核销截止日期
        @RequestParam(value = "totalPrice") Double totalPrice, // 订单总价
        @RequestParam(value = "state") Integer state) { // 订单状态
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
            // 检查上传的文件是否为空
            if (file.isEmpty()) {
                hashMap.put("message", "文件不能为空");
                return new ResponseEntity<>(hashMap, HttpStatus.BAD_REQUEST);
            }
            // 上传图片到七牛云并获取图片URL
            String imageUrl = qiniuUtil.uploadImage(file);

            // 创建一个新的订单对象并设置各项属性
            AsOrder asOrder = new AsOrder();
            asOrder.setId(id);
            asOrder.setAscommodityId(ascommodityId);
            asOrder.setUrl(imageUrl);
            asOrder.setOrderName(orderName);
            asOrder.setAddress(address);
            asOrder.setPrice(price);
            asOrder.setDescribe(describe);
            asOrder.setVerificationDeadline(verificationDeadline);
            asOrder.setTotalPrice(totalPrice);
            asOrder.setState(state);

            // 更新订单信息
            asOrderService.updateById(asOrder);
            hashMap.put("message", "修改订单");
            hashMap.put("imageUrl", imageUrl);
            return new ResponseEntity<>(hashMap, HttpStatus.OK);

        } catch (Exception e) {
            hashMap.put("message", "修改失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消指定的订单
     *
     * @param id 订单的ID
     * @return 包含取消结果的响应实体，包括状态和消息
     */
    @Operation(summary = "取消订单")
    @PostMapping("/deleteAsOrder")
    public ResponseEntity<Map<String, Object>> deleteAsOrder(@RequestParam(value = "id") Long id) {
        // 创建一个HashMap用于存储响应数据
        HashMap<String, Object> hashMap = new HashMap<>();

        // 尝试根据ID删除订单
        try {
            boolean removeById = asOrderService.removeById(id);

            // 根据删除结果设置响应状态和消息
            if (removeById) {
                hashMap.put("status", "success");
                hashMap.put("message", "订单已经取消");
                return new ResponseEntity<>(hashMap, HttpStatus.OK);
            } else {
                hashMap.put("status", "failure");
                hashMap.put("message", "未找到订单或订单无法取消");
                return new ResponseEntity<>(hashMap, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            // 异常情况下设置响应状态和消息
            hashMap.put("status", "error");
            hashMap.put("message", "发生错误" + e.getMessage());
            return new ResponseEntity<>(hashMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询订单名称对应的订单信息
     *
     * @param orderName 订单名称，用于查询
     * @return 包含查询结果的响应体，包括成功状态、数据和消息
     */
    @Operation(summary = "查询订单")
    @PostMapping("/selectOrderName")
    public ResponseEntity<Map<String, Object>> selectOrderName(@RequestParam(value = "orderName") String orderName) {
        // 初始化响应体
        Map<String, Object> response = new HashMap<>();
        try {
            // 调用服务层方法获取查询结果
            List<AsOrder> asOrders = asOrderService.selectOrderName(orderName);

            // 将结果放入响应体中
            response.put("success", true);
            response.put("data", asOrders);
            response.put("message", "查询成功");

            // 返回 200 OK 响应
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            // 异常处理
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());

            // 返回 500 内部服务器错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }


    /**
     * 查询所有订单
     *
     * @return 包含所有订单的响应实体
     */
    @Operation(summary = "查询所有订单")
    @GetMapping("/selectOrderName")
    public ResponseEntity<Map<String, Object>> selectOrderAll() {
        // 查询所有订单
        List<AsOrder> orders = asOrderService.list();

        // 构造响应数据
        Map<String, Object> response = new HashMap<>();
        response.put("orders", orders);

        // 返回响应
        return ResponseEntity.ok(response);
    }

}



